<?php

/**
 * Menashop
 *
 * LICENSE
 *
 * This source file is subject to the license that is bundled
 * with this project in the file LICENSE.txt
 *
 * @category   Zend
 * @package    OrderController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 * @version    1.0.0
 * @since      File available since Release 1.0.0
 */

/**
 * @category   Zend
 * @package    OrderController
 * @copyright  Copyright (c) 2011 Menashop UA Inc. (http://www.menashop.com.ua)
 * @license    LICENSE.txt
 */
class Storefront_OrderController extends Zend_Controller_Action
{

    /**
     * The logger
     * @var Zend_Log
     */
    protected $_logger;

    /**
     * Id of language
     * @var integer
     */
    protected $_languageId;

    /**
     * The model for cart
     * @var Storefront_Model_Cart
     */
    protected $_cartModel;

    /**
     * The config
     * @var Zend_Config
     */
    protected $_config;

    /**
     * Initialize the controller
     */
    public function init()
    {
        // Get logger
        $this->_logger = Zend_Registry::get('log');

        // Get language from locale
        $locale = Zend_Registry::get('Zend_Locale');
        $languageModel = new Storefront_Model_Language();
        $this->_languageId = $languageModel->findIdByShortCode($locale->getLanguage());
        $this->view->language = $locale->getLanguage();

        // Get category tree
        $categoryModel = new Storefront_Model_Category();
        $this->view->categoryTree = $categoryModel->getTree($this->_languageId);

        // Get cart
        $this->_cartModel = new Storefront_Model_Cart();
        $this->view->cartCount = $this->_cartModel->count();

        // Get current url without language
        $this->view->currentUrl = str_replace('/' . $locale->getLanguage(), '', $this->_request->getRequestUri());

        // Get config
        $this->_config = Zend_Registry::get('config');

        // Form for search
        $form = new Storefront_Model_FormSearch();
        $form->setAction('/' . $locale->getLanguage() . '/search');
        $this->view->formSearch = $form;

        $this->view->shopName = Zend_Registry::get('config')->shopName;
        $this->view->shopTitle = Zend_Registry::get('config')->shopTitle;
        $this->view->shopCity = Zend_Registry::get('config')->shopCity;
    }

    /**
     * Action for index
     */
    public function addAction()
    {
        // Check referrer
        if ($this->_cartModel->count() == 0) {
            $this->_redirect('/');
        }

        $form = new Storefront_Model_FormOrder();
        $form->setAction('/' . $this->view->language . '/order');

        // Has the order form been posted?
        if ($this->getRequest()->isPost()) {

            // If the submitted data is valid, attempt to authenticate the user
            if ($form->isValid($this->_request->getPost())) {
                $this->_processOrder($this->_request->getPost());
                $this->view->cartCount = $this->_cartModel->count();
            } else {
                $this->view->orderErrors = $form->getErrors();
            }
        }
        $this->view->formOrder = $form;

        // Get time of execution
        $startTime = Zend_Registry::get('startTime');
        $totalTime = round(microtime(true) - $startTime, 3);
        $this->_logger->debug(__METHOD__." spent $totalTime s");
    }

    /**
     * Process new order
     * @param array $data 
     */
    private function _processOrder($data)
    {
        // Find customer by phone
        $customerModel = new Storefront_Model_Customer();
        $customer = array();
        $customer['id'] = $customerModel->getIdByPhone($data['phone']);

        // Save customer details
        $customer['full_name'] = $data['full_name'];
        $customer['email'] = $data['email'];
        $customer['phone'] = $data['phone'];
        $customer['city'] = $data['city'];
        $customer['address'] = $data['address'];
        $customerId = $customerModel->save($customer);

        // Get data for order
        $order = array();
        $order['customer_id'] = $customerId;
        $productsResult = $this->_processOrderProducts();
        $order['total'] = $productsResult['total'];
        $this->view->total = $productsResult['total'];
        $this->view->totalCount = $productsResult['totalCount'];
        $this->view->products = $productsResult['products'];

        // Save order
        $orderModel = new Storefront_Model_Order();
        $orderId = $orderModel->save($order);
        $this->view->orderId = $orderId;

        // Save order products
        $this->_saveOrderProducts($orderId);

        // Send mail for order
        if ($data['email']) {
            $this->_sendEmail($data['email'], $data['full_name']);
        }
    }

    /**
     * Process order products
     */
    private function _processOrderProducts()
    {
        $cartItems = $this->_cartModel->getItems();

        // Get information about order products
        $productIds = array_keys($cartItems);
        $productModel = new Storefront_Model_Product();
        $products = $productModel->getByIds($productIds, $this->_languageId);

        // Calculate order total and get products count for view
        $total = 0;
        $totalCount = 0;
        foreach ($products as $product) {
            $product->count = $cartItems[$product->id];
            $total += $product->count * $product->price;
            $totalCount += $product->count;
        }
        $result = array();
        $result['products'] = &$products;
        $result['total'] = $total;
        $result['totalCount'] = $totalCount;
        return $result;
    }

    /**
     * Save order products
     * @param integer $orderId 
     */
    private function _saveOrderProducts($orderId)
    {
        // Save cart items to order
        $cartItems = $this->_cartModel->getItems();
        $orderProductModel = new Storefront_Model_OrderProduct();
        foreach ($cartItems as $productId => $count) {
            $orderProduct = array();
            $orderProduct['order_id'] = $orderId;
            $orderProduct['product_id'] = $productId;
            $orderProduct['count'] = $count;
            $orderProductModel->save($orderProduct);
        }

        // Clear cart
        $this->_cartModel->clear();
    }

    /**
     * Send mail about order
     * @param string $toEmail
     * @param string $toName 
     */
    private function _sendEmail($toEmail, $toName)
    {
        // Create a new mail object
        $mail = new Zend_Mail('UTF8');

        // Set the e-mail from address, to address, and subject
        $mail->setFrom($this->_config->email->from, $this->_config->email->name);
        $mail->addTo($toEmail, $toName);
        $this->view->shopName = $this->_config->shopName;
        $mail->setSubject($this->view->render('order/email_subject.phtml'));

        // Set the e-mail message text
        $mail->setBodyHtml($this->view->render('order/email_body.phtml'));
        // Send the e-mail
        $mail->send();
    }

}

